#include "QtUI/NewProjectCommand.qth"
#include "QtUI/NewProjectCommand.moh"
#include "QtUI/ProjectInformationDialog.qth"
#include "QtUI/ProjectInformationWidget.qth"
#include "QtUI/CloseProjectCommand.qth"
#include "QtUI/ProjectCommands.qth"
#include "AbsUI/UIConfigurationCenter.hpp"
#include "Model/Project.hpp"
#include "Storage/ConnectionConfig.hpp"
#include "Storage/StorageFactory.hpp"
#include "Storage/ProjectStorage.hpp"
#include "Storage/PackageStorage.hpp"
#include "Ctrl/ControlCenter.hpp"
#include <QtGui/QMessageBox>

namespace QtUI
{

NewProjectCommand::NewProjectCommand( QAction* pBoundAction)
	: UICommandBase( pBoundAction)
{
}

// ---------------------------------------------------------------------------------------------------------------------

bool NewProjectCommand::execute( bool /*checked*/ /*= false*/)
{
	ProjectInformationDialog dlg( AbsUI::UIConfigurationCenter::uiConfigCenter().connCfgCollection());
	int result = dlg.exec();
	while( result == QDialog::Accepted)
	{
		using namespace Model;
		using namespace Storage;
		
		try
		{
			// Create storage policy factory first
			const ConnectionConfig* pConnCfg = dlg.prjInfoWidget()->connectionConfig();
			std::auto_ptr< StorageFactory> pPolicyFactory( pConnCfg->createStorageFactory());
			std::auto_ptr< Project> pProject( new Project( 
				dlg.prjInfoWidget()->projectName().toStdString(),
				dlg.prjInfoWidget()->description().toUtf8().data()));

			// Close current project
			CloseProjectCommand& closeCmd = dynamic_cast< CloseProjectCommand&>( ProjectCommands::getCloseProjectCommand());
			if( closeCmd.canCloseProject())
			{
				pPolicyFactory->getProjectStorage().pushCommand( pPolicyFactory->createProjectCreationCommand( *pProject));
				// Don't forget to create the root package on the storage as well.
				pPolicyFactory->getPackageStorage().pushCommand( pPolicyFactory->createPackageCreationCommand( pProject->rootPackage()));
				Ctrl::ControlCenter::instance().prjController().setControlledProject( pProject.release(), pPolicyFactory.release());

				return true;
			}
			// ELSE:
			// If the current project couldn't be saved or the user have chosen not to close current project, then try 
			// new project again.
		}
		catch( std::exception& e)
		{
			QMessageBox::critical( 
				NULL, 
				tr( "Create new project"), 
				tr( "There was an error while creating the new project:\n") + QString( e.what()));
			return false;
		}
		dlg.exec();
	}
}

} // namespace QtUI
